<template>
    <div class="view_operation_category">
        <card title="产品类别管理">
            <template v-slot:actions>
                <el-button type="primary" @click="add">添加产品类别</el-button>
            </template>
            <template v-slot:default>
                <el-table :data="tableData" row-key="catalogId" :tree-props="{ children: 'childs' }">
                    <el-table-column prop="categoryName" label="类名" />
                    <el-table-column prop="catalogId" label="id" />
                    <el-table-column prop="catLevel" label="分类层级" />
                    <el-table-column prop="indexShow" label="三级类目">
                        <template v-slot="{ row: { indexShow } }">
                            <span>{{ indexShow ? '是' : '否' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="showStatus" label="是否显示">
                        <template v-slot="{ row: { showStatus } }">
                            <span>{{ showStatus ? '显示' : '隐藏' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否溯源">
                        <template v-slot="{ row: { isTracker } }">
                            <el-tag :type="categoryTraceabilityStatus[+isTracker].tagType">
                                {{ categoryTraceabilityStatus[+isTracker].text }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="标签">
                        <template v-slot="{ row }">
                            {{ categoryLabels[row.flag] }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="catUnit" label="单位" />
                    <el-table-column label="图标">
                        <template #default="{ row }">
                            <img :src="row.icon" :alt="row.icon" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="catSort" label="排序" />
                    <el-table-column prop="isTracker" label="操作">
                        <template v-slot="{ row, row: { catalogId } }">
                            <el-button type="text" @click="edit(row)">编辑</el-button>
                            <el-button type="text" @click="_delete(catalogId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </card>

        <!-- 添加/编辑产品类别对话框 -->
        <el-dialog :visible.sync="visible" :title="dialogTitle" @closed="handleClosed">
            <template v-slot:default>
                <el-form label-position="top">
                    <el-form-item label="分类名称">
                        <el-input v-model="form.categoryName"></el-input>
                    </el-form-item>
                    <el-form-item label="上级分类">
                        <treeselect v-model="form.parentId" :options="parentOptions" />
                    </el-form-item>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="单位">
                                <el-input v-model="form.catUnit"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="标签">
                                <el-select v-model="form.flag">
                                    <el-option
                                        v-for="(value, key) in categoryLabels"
                                        :key="value"
                                        :label="value"
                                        :value="+key"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="排序">
                                <el-input v-model="form.catSort" type="number" min="0" max="99"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="图标">
                        <el-upload
                            drag
                            :action="uploaderData.action"
                            :data="uploaderData.data"
                            :auto-upload="false"
                            :show-file-list="false"
                            :on-change="handleFileChange"
                            :on-success="handleFileUploadSuccess"
                            ref="uploader"
                        >
                            <template v-if="objectUrl">
                                <img class="preview_image" :src="objectUrl" />
                            </template>
                            <template v-else>
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="备选项">
                        <el-checkbox v-model="form.indexShow">首页显示：三级类目</el-checkbox>
                        <el-checkbox v-model="form.showStatus">是否显示</el-checkbox>
                        <el-checkbox v-model="form.isTracker">是否溯源</el-checkbox>
                    </el-form-item>
                </el-form>
            </template>
            <template v-slot:footer>
                <el-button type="primary" @click="save">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getDeletionOptions, getQueryOptions } from '../../mixins';
import { v4 as getUUIDV4 } from 'uuid';
import Treeselect from '@riophae/vue-treeselect';

const defaultFormData = {
    parentId: 0,
    categoryName: '',
    catLevel: '',
    catSort: 99,
    icon: 'null',
    catUnit: '',
    indexShow: false,
    isTracker: false,
    showStatus: false,
    flag: 0,
};

const defaultFormDataCopied = Object.assign({}, defaultFormData);

export default {
    data() {
        return {
            visible: false,
            tableData: [],

            form: defaultFormData,
            parentOptions: null,

            editing: false,

            uploaderData: {
                action: '',
                data: null,
            },

            fileInfo: null,

            // 文件blob链接
            objectUrl: '',
        };
    },

    components: { Treeselect },

    mixins: [
        getQueryOptions({
            apiurl: '/yxl/pms/findPmsCategory',
            fnAfterQuery: 'queryCallback',
        }),
        getDeletionOptions({
            apiurl: '/yxl/pms/deletePmsCategory',
            params: 'catalogId',
        }),
    ],

    computed: {
        // 对话框标题
        dialogTitle() {
            return this.editing ? '编辑产品类别' : '添加产品类别';
        },

        // 类别的可溯源性状态
        categoryTraceabilityStatus() {
            return {
                0: { text: '不可溯源', tagType: 'warning' },
                1: { text: '可溯源' },
            };
        },

        // 类别标签
        categoryLabels() {
            return { 0: '其他', 1: '冻品', 2: '冰鲜' };
        },
    },

    methods: {
        queryCallback(res) {
            this.parentOptions = Object.freeze(
                [{ id: 0, label: '根类别' }].concat(
                    (function _(treeData) {
                        let arr = [];

                        treeData = JSON.parse(JSON.stringify(treeData));

                        for (let i = 0; i < res.length; i++) {
                            const item = res[i],
                                obj = { id: item.catalogId, label: item.categoryName };

                            if (item.childs && item.childs.length) {
                                obj.children = [];

                                for (let j = 0; j < item.childs.length; j++) {
                                    const subitem = item.childs[j];
                                    obj.children.push({ id: subitem.catalogId, label: subitem.categoryName });
                                }
                            }

                            arr.push(obj);
                        }
                        return arr;
                    })(res)
                )
            );
        },

        add() {
            this.editing = false;
            this.visible = true;
        },

        edit(row) {
            this.form.catalogId = row.catalogId;
            this.form.parentId = row.parentId;
            this.form.categoryName = row.categoryName;
            this.form.indexShow = row.indexShow;
            this.form.showStatus = row.showStatus;
            this.form.catSort = row.catSort;
            this.form.icon = row.icon;
            this.form.catUnit = row.catUnit;
            this.form.isTracker = row.isTracker;
            this.form.flag = row.flag;
            // 对象url
            this.objectUrl = row.icon;
            this.editing = true;
            this.visible = true;
        },

        save() {
            if (this.fileInfo) {
                let uuid = getUUIDV4();
                let fileName = this.fileInfo.name;
                let fileExpansion = fileName.substr(fileName.lastIndexOf('.'));

                this.$get('/yxl/oss/policy').then(res => {
                    let path = `${res.dir}/${uuid}${fileExpansion}`;

                    this.form.icon = `${res.host}/${path}/catalog_list`;

                    this.uploaderData.action = res.host;

                    this.uploaderData.data = {
                        key: path,
                        policy: res.policy,
                        signature: res.signature,
                        OSSAccessKeyId: res.accessid,
                        success_action_status: '200',
                    };

                    this.$nextTick(this.$refs.uploader.submit);
                });
            } else {
                this.handleFileUploadSuccess();
            }
        },

        // 处理对话框关闭
        handleClosed() {
            Object.assign(this.form, defaultFormDataCopied);
            delete this.form.catalogId;

            // 清除文件实例
            this.fileInfo = null;
            this.objectUrl = '';
        },

        // 处理文件变化
        handleFileChange(file, fileList) {
            // 文件列表数量大于一时删除第一个，限制上传文件数量是一
            if (fileList.length > 1) {
                fileList.shift();
            }

            // 保存当前文件对象于实例
            this.fileInfo = file.raw;

            // 如果原先存有链接则销毁原先的链接
            if (this.objectUrl) {
                URL.revokeObjectURL(this.objectUrl);
            }

            // 创建blob链接预览图片
            this.objectUrl = URL.createObjectURL(file.raw);
        },

        // 处理文件上传成功
        handleFileUploadSuccess() {
            this.$put(`/yxl/pms/${this.editing ? 'update' : 'save'}PmsCategory`, this.form).then(res => {
                this.visible = false;
                this.query();
            });
        },
    },
};
</script>